﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

namespace AliCMS.UserModule
{
    public class WxPayUnifiedOrder : Page
    {
		protected string Params = "{}";

		public WxPayUnifiedOrder(string pathInTemplate) : base(pathInTemplate)
        {
        }

		/* 参数：
		**（1）OutTradeNo：订单ID，必填；
		**（2）Amount：支付金额，单位为元，必填；
		**（3）NotifyUrl：异步通知网址，必填；
		**（4）OpenID：用户OpenID，必填；
		**（5）SubMerchantID：特约商户号，必填；
		**/
		protected override void OnLoad(EventArgs e)
		{
			string outTradeNo = Request.QueryString["OutTradeNo"];
			if (String.IsNullOrEmpty(outTradeNo))
			{
				Manager.Log("UserModule - WxPayUnifiedOrder - OutTradeNo必传", "", PageLang);
				return;
			}

			if (String.IsNullOrEmpty(Request.QueryString["Amount"]) || !Regex.IsMatch(Request.QueryString["Amount"], @"^\d+(\.\d+)?$"))
			{
				Manager.Log("UserModule - WxPayUnifiedOrder - Amount必传并且是数字", "Amount：" + Request.QueryString["Amount"], PageLang);
				return;
			}

			try
			{
				//准备数据
				WxPayDataV2 data = new WxPayDataV2(WxPayPartner.MERCHANT_API_KEY);
				data.SetValue("appid", WxPayPartner.WXPP_APPID);
				data.SetValue("mch_id", WxPayPartner.MERCHANT_ID);
				if (!String.IsNullOrEmpty(Request.QueryString["SubAppID"]))
					data.SetValue("sub_appid", Request.QueryString["SubAppID"]);
				data.SetValue("sub_mch_id", Request.QueryString["SubMerchantID"]);
				data.SetValue("device_info", "WEB");
				data.SetValue("nonce_str", WxPayPartner.GetNonceStr());
				data.SetValue("body", outTradeNo);
				data.SetValue("out_trade_no", outTradeNo);
				data.SetValue("total_fee", Convert.ToInt32(Convert.ToDecimal(Request.QueryString["Amount"]) * 100));
				data.SetValue("spbill_create_ip", Request.UserHostAddress);
				data.SetValue("notify_url", Request.QueryString["NotifyUrl"]);
				data.SetValue("trade_type", "JSAPI");
				data.SetValue("openid", Request.QueryString["OpenID"]);
				if (Request.QueryString["ProfitSharing"] != "false")
					data.SetValue("profit_sharing", "Y");
				data.SetValue("sign_type", "HMAC-SHA256");
				data.SetValue("sign", data.MakeSign());

				//debug
				//Manager.Log("统一下单 - 准备数据", data.ToXml(), PageLang);

				//请求Url
				HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.mch.weixin.qq.com/pay/unifiedorder");
				request.Method = "POST";
				request.Timeout = 6 * 1000;
				request.ContentType = "text/xml";
				byte[] buffer = System.Text.Encoding.UTF8.GetBytes(data.ToXml());
				request.ContentLength = buffer.Length;

				//往服务器写入数据
				Stream reqStream = request.GetRequestStream();
				reqStream.Write(buffer, 0, buffer.Length);
				reqStream.Close();

				//获取服务端返回
				HttpWebResponse response = (HttpWebResponse)request.GetResponse();
				StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
				string result = sr.ReadToEnd().Trim();
				sr.Close();

				//统一订单数据
				data.Clear();
				data.FromXml(result);

				//debug
				//Manager.Log("统一下单 - 结果", result, PageLang);

				//生成支付参数
				if (Convert.ToString(data.GetValue("return_code")) == "FAIL")
				{
					Manager.Log("UserModule - WxPayUnifiedOrder - 统一下单失败 - return_code == FAIL", "result：" + result, PageLang);

					Params = "{\"error\":1,\"errmsg\":\"" + data.GetValue("return_msg") + "\"}";
				}
				else if (Convert.ToString(data.GetValue("result_code")) == "FAIL")
				{
					Manager.Log("UserModule - WxPayUnifiedOrder - 统一下单失败 - result_code == FAIL", "result：" + result, PageLang);

					Params = "{\"error\":2,\"errmsg\":\"" + data.GetValue("err_code_des") + "\"}";
				}
				else
				{
					WxPayDataV2 jsApiParam = new WxPayDataV2(WxPayPartner.MERCHANT_API_KEY);
					jsApiParam.SetValue("appId", WxPayPartner.WXPP_APPID);
					jsApiParam.SetValue("timeStamp", WxPayPartner.GetTimestamp());
					jsApiParam.SetValue("nonceStr", WxPayPartner.GetNonceStr());
					jsApiParam.SetValue("package", "prepay_id=" + data.GetValue("prepay_id"));
					jsApiParam.SetValue("signType", "HMAC-SHA256");
					jsApiParam.SetValue("paySign", jsApiParam.MakeSign());

					Params = jsApiParam.ToJson();
				}
			}
			catch (Exception exp)
			{
				Manager.Log("UserModule - WxPayUnifiedOrder - Exception", exp.ToString(), PageLang);
				Params = "{\"error\":3,\"errmsg\":\"发生异常，请与管理员联系！\"}";
			}
		}
	}
}
